package com.example.demospringmybatisplus.service;

import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;

import com.example.demospringmybatisplus.annotation.SecureInvoke;

import cn.hutool.core.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 发送mq工具类
 *
 * @author hauhua
 * @DATE 2025/1/21
 */
@Slf4j
public class MQProducerService {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    public void sendMsg(String topic, Object body) {
        Message<Object> build = MessageBuilder.withPayload(body).build();
        rocketMQTemplate.send(topic, build);
    }

    /**
     * 发送可靠消息，在事务提交后保证发送成功
     *
     * @param topic
     * @param body
     * @param key
     */
    @SecureInvoke
    public void sendSecureMsg(String topic, Object body, Object key) {
        // 通过切面实现本地消息表，因为要在此方法执行前将数据保存到本地消息表，进行功能增强
        // 模拟发送mq消息有1/3概率失败，发送失败之后会抛出异常，下次会重试
        if(RandomUtil.randomInt(3) >= 1){
            log.info("sendSecureMsg fail");
            throw new IllegalStateException();
        }
        
        Message<Object> build = MessageBuilder
                .withPayload(body)
                .setHeader("KEYS", key)
                .build();
        log.info("sendSecureMsg start");
        rocketMQTemplate.send(topic, build);
        log.info("sendSecureMsg end");
    }
}
